<?php
class Loop{
	
	public $values = null;
	public $parser = null;
	public $dom = null;
	
	public function Loop($parser, $html, $values){
		$this->parser = $parser;
		$this->values = $values;

		$new_values = array();
		$index = 0;
		foreach($this->values as $key => $arr){
			if(is_numeric($key) && !is_array($arr)){
				$arr = array('row_key'=>$key, 'row_value'=>$arr);
			}
			$arr['row_index'] = $index;
			$new_values[] = $arr;
			$index++;
		}
		$this->values = $new_values;
		
		
		$this->dom = new simple_html_dom;
		$this->dom->load($html, false);
	}
	
	public function evaluate(){
		if(count($this->values)){
			return $this->eval_rows();
		}else{
			return $this->eval_no_rows();
		}
	}
	
	public function eval_rows(){
		$row = $this->dom->find('row', 0);
		$new_html = array();
		preg_match_all('`\{\$(.*)\}`',$row->innertext(),$vars);
		foreach($this->values as $row_values){
			$temp_html = $row->innertext;
			if($vars){
				foreach($vars[1] as $index => $var_logic){
					$var = new Variable($var_logic, $row_values, $row_values);
					$eval = $var->evaluate();
					if($eval['tag'] || $eval['ptag']){
						if($eval['tag']){
							$tagbody = $eval['tag'];
							$delete_content = true;
						}else{
							$tagbody = $eval['ptag'];
							$delete_content = false;
						}
						$pos = strpos($temp_html, $vars[0][$index]);
						$dom = new simple_html_dom;
						$dom->load($temp_html, false);
						$this->parser->delete_tag($dom, $tagbody, $pos, $delete_content);
						$temp_html = $dom->save();
					}
					$temp_html = str_replace($vars[0][$index], $eval['replacement'], $temp_html);
				}
			}
			$new_html[] = $temp_html;
		}
		return implode("\n", $new_html);
	}
	
	public function eval_no_rows(){
		$row = $this->dom->find('row[nodata]', 0);
		if($row){
			preg_match_all('`\{\$(.*)\}`',$row->innertext(),$vars);
			$new_html = $row->innertext;
			if($vars){
				foreach($vars[1] as $index => $var_logic){
					$var = new Variable($var_logic, $this->parser->vars);
					$eval = $var->evaluate();
					if($eval['tag'] || $eval['ptag']){
						if($eval['tag']){
							$tagbody = $eval['tag'];
							$delete_content = true;
						}else{
							$tagbody = $eval['ptag'];
							$delete_content = false;
						}
						$pos = strpos($new_html, $vars[0][$index]);
						$dom = new simple_html_dom;
						$dom->load($new_html, false);
						$this->parser->delete_tag($dom, $tagbody, $pos, $delete_content);
						$new_html = $dom->save();
					}
					$new_html = str_replace($vars[0][$index], $eval['replacement'], $new_html);
				}
			}
			return $new_html;
		}else{
			return '';
		}
	}
}
?>